- Published on
Codable in Swift
- Authors
- Name
在 SwiftData 中添加自定义类型时,需要该类型符合 Codable 协议。有点没搞明白为什么?
什么是Codable
Codable
A type that can convert itself into and out of an external representation.
typealias Codable = Decodable & Encodable
Discussion
Codable is a type alias for the Encodable and Decodable protocols. When you use Codable as a type or a generic constraint, it matches any type that conforms to both protocols.
Decodable
A type that can decode itself from an external representation. 允许从外部表示解码为对象。
Encodable
A type that can encode itself to an external representation. 允许对象编码为外部表示(如 JSON、plist)。
Codable的用途
- 将Swift对象和外部数据表示进行互相转换
- 在网络请求API中处理数据
- 在SwiftData中存储或读取复杂数据(如[String],或自定义数据类型)
符合Codable协议的基本要求
结构体或类的属性必须是 Codable 兼容的类型(基本类型如 String、Int、Double,以及数组 [T]、字典 [String: T] 等,其中 T 也需符合 Codable)。 Swift 编译器会自动为符合条件的类型生成 Codable 实现,前提是所有属性都符合 Codable。